// axios默认配置，如如特需需求，不用修改
import axios from 'axios';
import {store} from "../store";
import qs from 'qs';
import  {message}  from '../utils/resetMessage'

/**
 *
 axios 默认异步，例子：getvip() 在gettoken()执行完成后执行
 methods: {
   async gettoken() {
     console.log(111)
     var api = 'http://192.168.1.9/au?ame=vu&pword=n'
     await axios.get(api).then((response) => {                          //请求+await
       this.token = response.data.data.token
     })
   },
   async getvip() {
     await this.gettoken()      // 先获取token值                         请求+await
     this.listLoading = true
     var api = `http://192.168.1.9/history?mode=sreach&token=`
     api = api + this.token
     axios.post(api, this.postdata).then((response) => {
       console.log(response.data.data)
       this.data = response.data.data
       this.listLoading = false
       return
     }, (err) => {
       console.log(err)
     })
   },
}
 * @param err
 */

function  handleErrApi(err) {
  let error="";
  if(err.response===undefined){
    error="请求超时！";
  }else if(err.response.data.errMsg===undefined){
    if("arraybuffer"==err.config.responseType){
      let enc = new TextDecoder("utf-8");
      error=JSON.parse(enc.decode(new Uint8Array(err.response.data))).errMsg;
    }else{
      error="未知错误！";
    }
  }else {
    error=err.response.data.errMsg;
  }
  message.error(error);
}

// 一些公共的属性可以放在这里
const instance = axios.create({
  timeout:60000
});
//请求之前添加配置
const axiosConfig=(config)=>{
  config.headers.departmentRoleId=store.getters.currentRole || ''//添加请求头
  return config
}
//请求之前添加配置，出现错误
const configError=(error)=>{
  return Promise.reject(error);
}
instance.interceptors.request.use(axiosConfig,configError);

//接口响应成功 200
const afterSuccess=(response)=>{
  return response
}
//接口响应失败
const afterError=(error)=>{
  handleErrApi(error)
  return Promise.reject(error);
}
instance.interceptors.response.use(afterSuccess,afterError);
export default instance;

